﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;  //WebClient
using System.Text.RegularExpressions; //正则表达式
using Microsoft.Win32;//RegistryKey
using System.IO;//Stream

namespace GoatClubPlus
{
    public partial class LoginForm : Form
    {

        public LoginForm()
        {
            InitializeComponent();
        }

        //定义委托 用于等下支线程修改主线程的控件值
        public delegate void SetTextCallback(string text);

        //定义一个CookieContainer 之后Post用
        CookieContainer cookie = new CookieContainer();

        bool lgcompeleted; bool lgcompeleted2;

        private void LoginForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            getnews.RunWorkerAsync(); //启动获得最新消息线程
            string name = ""; string rmp = ""; string avatar = "";
            RegistryKey Key=Registry.LocalMachine;
            RegistryKey myreg = Key.OpenSubKey("software\\GoatClub");
            name = myreg.GetValue("Name").ToString();
            rmp = myreg.GetValue("RPW").ToString();
            avatar = myreg.GetValue("Avatar").ToString();
            if (avatar != "")
            {
                pictureBox1.ImageLocation=avatar;
                //异步加载头像
                pictureBox1.LoadAsync();
            }
            textBox1.Text = name;
            if (rmp == "true")
            {
                checkBox1.Checked = true;
                string password = myreg.GetValue("Password").ToString();
                string pw2 = "";
                System.Text.ASCIIEncoding code = new System.Text.ASCIIEncoding();
                //解密算法
                foreach (char flag in code.GetBytes(password))
                {
                    int tmp = (int)flag;
                    if (tmp < 50)
                    {
                        tmp += 127;
                    }
                    tmp -= 50;
                    byte[] byteArray = new byte[] { (byte)tmp };
                    pw2 += code.GetString(byteArray);
                }
                textBox2.Text = pw2;
            }
        }

        //设置文本函数
        private void setText(string text)
        {
            if (label3.InvokeRequired)
            {
                SetTextCallback s = new SetTextCallback(setText);
                Invoke(s, new string[] { text });
            }
            else
            {
                label3.Text = text;
            }
        }

        private void getnews_DoWork(object sender, DoWorkEventArgs e)
        {
            //获取羊羊俱乐部网页源码
            string url = "http://goatclub.sinaapp.com";
            WebClient myWebClient=new WebClient();
            byte[] myDataBuffer=myWebClient.DownloadData(url);
            string html=Encoding.UTF8.GetString(myDataBuffer);
            //获取最新消息
            string start = "style="+"\""+"font-weight: bold;text-decoration: underline;color: red"+"\""+">";
            string end="</a></div>";
            Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
            string zxxx= rg.Match(html).Value;
            zxxx = "最新消息:" + zxxx;
            //MessageBox.Show("最新消息:"+zxxx);
            setText(zxxx);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://goatclub.sinaapp.com/member.php?mod=register");
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://wpa.qq.com/pa?p=2:609741313:41");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            loginThread.RunWorkerAsync();//启动登录支线程
            button1.Enabled = false; button1.Text = "登陆中";
            RegistryKey key = Registry.LocalMachine;
            RegistryKey software = key.OpenSubKey("software\\GoatClub", true);
            bool rmpw=false;
            //判断是否选择了"记住密码"项
            if (checkBox1.Checked == true)
            {
               rmpw = true;
               software.SetValue("RPW", "true");
            }            
            software.SetValue("Name", textBox1.Text);
            if (rmpw == true)
            {
                //开始加密密码
                string pw2 = "";
                System.Text.ASCIIEncoding code = new System.Text.ASCIIEncoding();
                foreach (char flag in code.GetBytes(textBox2.Text))
                {
                    int tmp = (int)flag;
                    tmp += 50;
                    if (tmp > 127)
                    {
                        tmp -= 127;
                    }
                    byte[] byteArray = new byte[] { (byte)tmp };
                    pw2 += code.GetString(byteArray);
                }
                //写入注册表
                software.SetValue("Password", pw2);
                software.Close(); key.Close();
            }
        }

        private void loginThread_DoWork(object sender, DoWorkEventArgs e)
        {
            string name = textBox1.Text; string pw = textBox2.Text; string name2 = "";
            //UrlEncode
            StringBuilder sb = new StringBuilder();
            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(name); //默认是System.Text.Encoding.Default.GetBytes(str)
            for (int i = 0; i < byStr.Length; i++)
            {
                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
            }
            name2 = sb.ToString();
            string postDataStr = "username=" + name2 + "&password=" + pw + "&quickforward=yes&handlekey=ls";
            //Post数据到服务器
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://goatclub.sinaapp.com/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1");
            
            //设置HttpWebRequest的CookieContainer为刚才建立的那个myCookieContainer 
            if (cookie.Count == 0)
            {
                request.CookieContainer = new CookieContainer();
                cookie = request.CookieContainer;
            }
            else
            {
                request.CookieContainer = cookie;
            }

            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataStr.Length;
            Stream myRequestStream = request.GetRequestStream();
            StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
            //把数据写入HttpWebRequest的Request流 
            myStreamWriter.Write(postDataStr);
            myStreamWriter.Close();
            //获取一个包含url的Cookie集合的CookieCollection 
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();
            //把数据从HttpWebResponse的Response流中读出 
            myStreamReader.Close();
            myResponseStream.Close();
            
            //判断是否成功登录
            bool lgfailed = retString.Contains("登录失败");
            if (lgfailed == true)
            {
                //string start = "root><![CDATA[";
                //string end = "<script type=";
                //Regex rg = new Regex("(?<=(" + start + "))[.\\s\\S]*?(?=(" + end + "))", RegexOptions.Multiline | RegexOptions.Singleline);
                MessageBox.Show("登录失败！","消息:");
                lgcompeleted2 = true;
            }
            else 
            {
                MessageBox.Show("登陆成功！","消息:");
                lgcompeleted = true;
            }
        }

        private void getnews_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //挂起
            getnews.CancelAsync();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (lgcompeleted == true)
            {
                MainForm mf = new MainForm();
                mf.Show();
                this.Hide();
                timer1.Enabled = false;
            }
            if (lgcompeleted2 == true)
            {
                button1.Enabled = true; button1.Text = "登录";
                lgcompeleted2 = false;
            }
        }
    }
}
